import 'dart:convert';

import 'package:flutter/services.dart' show rootBundle;
import 'package:flutter_reader/model/article.dart';
import 'package:flutter_reader/model/chapter.dart';

import 'package:flutter_reader/model/novel.dart';

class Request {
  static const String baseUrl = 'http://www.shuqi.com/';

  static Future<dynamic> get({String action, Map params}) async {
    return Request.mock(action: action, params: params);
  }

  static Future<dynamic> post({String action, Map params}) async {
    return Request.mock(action: action, params: params);
  }

  static Future<dynamic> mock({String action, Map params}) async {
    var responseStr = await rootBundle.loadString('mock/$action.json');
    var responseJson = json.decode(responseStr);
    return responseJson['data'];
  }

  // 获取书架列表
  static Future<List<Novel>> getFavoriteNovels() async {
    List<Novel> favoriteNovels = [];
    List<dynamic> favoriteResponse = await Request.get(action: 'bookshelf_4');
    favoriteResponse.forEach((data) {
      favoriteNovels.add(Novel.fromJson(data));
    });
    return favoriteNovels;
  }

  // 获取书籍详情
  static Future<Novel> getNovelDetail(String novelId) async {
    var novelResponse =
        await Request.post(action: 'novel_detail', params: {'id': novelId});
    return Novel.fromJson(novelResponse);
  }

  // 获取推荐列表
  static Future<List<Novel>> getNovelRecommend(String novelId) async {
    var recommendResponse =
        await Request.post(action: 'novel_recommend', params: {'id': novelId});
    List<Novel> recommendNovels = [];
    recommendResponse.forEach((data) {
      recommendNovels.add(Novel.fromJson(data));
    });
    return recommendNovels;
  }

  // 获取章节列表
  static Future<List<Chapter>> getNovelChapters() async {
    List<dynamic> chaptersResponse = await Request.get(action: 'catalog');
    List<Chapter> chapters = [];
    chaptersResponse.forEach((data) {
      chapters.add(Chapter.fromJson(data));
    });
    return chapters;
  }

  // 获取章节内容
  static Future<Article> getArticle(int articleId) async {
    var response = await Request.post(
        action: 'novel_detail', params: {'id': 'article_$articleId'});
    return Article.fromJson(response);
  }
}
